package com.powernode.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AuthenticationEntryPointImpl
 * @Description 处理没有携带token的请求
 * @Date 2024/07/21 15:04
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    /**
     * 未登录时，访问受保护的资源时，会调用此方法
     * @param request 请求
     * @param response 响应
     * @param authException 认证异常
     * @throws IOException io异常
     * @throws ServletException servlet异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 设置响应头
        response.setContentType(HttpConstants.APPLICATION_JSON);
        request.setCharacterEncoding(HttpConstants.UTF_8);
        // 结果返回
        Result<Object> failResult = Result.fail(BusinessEnum.UN_AUTHORIZATION);
        String responseStr = new ObjectMapper().writeValueAsString(failResult);
        PrintWriter writer = response.getWriter();
        writer.write(responseStr);
        writer.flush();
        writer.close();
    }
}
